<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="房屋名" prop="houseName">
        <el-input v-model="queryParams.houseName" placeholder="请输入房屋名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="房屋编号" prop="houseCode">
        <el-input v-model="queryParams.houseCode" placeholder="请输入房屋编号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="省份" prop="province">
        <el-select v-model="queryParams.province" placeholder="请选择省份" clearable @change="handleQueryProvinceChange">
          <el-option
            v-for="item in provinceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-select v-model="queryParams.city" placeholder="请选择城市" clearable @change="handleQueryCityChange">
          <el-option
            v-for="item in queryCityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="区域" prop="district">
        <el-select v-model="queryParams.district" placeholder="请选择区域" clearable>
          <el-option
            v-for="item in queryDistrictOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="风险等级" prop="riskLevel">
        <el-select v-model="queryParams.riskLevel" placeholder="请选择风险等级" clearable>
          <el-option
            v-for="dict in dict.type.house_risk_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['house:house:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['house:house:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="houseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="房屋ID" align="center" prop="houseId" />
      <el-table-column label="房屋名称" align="center" prop="houseName" />
      <el-table-column label="房屋编号" align="center" prop="houseCode" />
      <el-table-column label="地址" align="center" prop="address" :show-overflow-tooltip="true"/>
      <el-table-column label="建筑面积" align="center" prop="buildingArea" />
      <el-table-column label="建造日期" align="center" prop="buildDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.buildDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="风险等级" align="center" prop="riskLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.house_risk_level" :value="scope.row.riskLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['house:house:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['house:house:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改房屋对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-tabs v-model="activeTab">
        <!-- 基本信息标签页 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="房屋名称" prop="houseName">
                  <el-input v-model="form.houseName" placeholder="请输入房屋名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="房屋编号" prop="houseCode">
                  <el-input v-model="form.houseCode" placeholder="请输入房屋编号" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="省份" prop="province">
                  <el-select v-model="form.province" placeholder="请选择省份" @change="handleProvinceChange">
                    <el-option
                      v-for="item in provinceOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="城市" prop="city">
                  <el-select v-model="form.city" placeholder="请选择城市" @change="handleCityChange">
                    <el-option
                      v-for="item in cityOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="区域" prop="district">
                  <el-select v-model="form.district" placeholder="请选择区域" @change="handleDistrictChange">
                    <el-option
                      v-for="item in districtOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="街道" prop="street">
                  <el-select v-model="form.street" placeholder="请选择街道" @change="handleStreetChange">
                    <el-option
                      v-for="item in streetOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="居委" prop="community">
                  <el-select 
                    v-model="form.community" 
                    placeholder="请选择居委" 
                    @change="handleCommitteeChange"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in committeeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="详细地址" prop="address">
                  <el-input v-model="form.address" placeholder="请输入详细地址" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input-number v-model="form.longitude" :precision="6" :step="0.000001" placeholder="请输入经度" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input-number v-model="form.latitude" :precision="6" :step="0.000001" placeholder="请输入纬度" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>

        <!-- 房屋信息标签页 -->
        <el-tab-pane label="房屋信息" name="house">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="土地证号" prop="landCertificate">
                  <el-input v-model="form.landCertificate" placeholder="请输入土地证号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="占地面积" prop="landArea">
                  <el-input-number v-model="form.landArea" :precision="2" :step="0.01" placeholder="请输入占地面积" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="土地性质" prop="landNature">
                  <el-select v-model="form.landNature" placeholder="请选择土地性质">
                    <el-option
                      v-for="dict in dict.type.house_land_nature"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产权性质" prop="propertyNature">
                  <el-select v-model="form.propertyNature" placeholder="请选择产权性质">
                    <el-option
                      v-for="dict in dict.type.house_property_nature"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="产权单位" prop="propertyOwner">
                  <el-input v-model="form.propertyOwner" placeholder="请输入产权单位（人）" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产权证号" prop="propertyCertificate">
                  <el-input v-model="form.propertyCertificate" placeholder="请输入产权证号" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="公房面积" prop="publicArea">
                  <el-input-number v-model="form.publicArea" :precision="2" :step="0.01" placeholder="请输入公房面积" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="售后面积" prop="afterSaleArea">
                  <el-input-number v-model="form.afterSaleArea" :precision="2" :step="0.01" placeholder="请输入售后房面积" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="公房户数" prop="publicHouseCount">
                  <el-input-number v-model="form.publicHouseCount" :min="0" placeholder="请输入直管公房数" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="售后户数" prop="afterSaleCount">
                  <el-input-number v-model="form.afterSaleCount" :min="0" placeholder="请输入售后房户数" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="其他户数" prop="otherTypeCount">
                  <el-input-number v-model="form.otherTypeCount" :min="0" placeholder="请输入其他类型户数" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="主用人数" prop="mainUserCount">
                  <el-input-number v-model="form.mainUserCount" :min="0" placeholder="请输入主用人数" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="建筑面积" prop="buildingArea">
                  <el-input-number v-model="form.buildingArea" :precision="2" :step="0.01" placeholder="请输入建筑面积" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="建造日期" prop="buildDate">
                  <el-date-picker
                    v-model="form.buildDate"
                    type="date"
                    placeholder="选择建造日期"
                    value-format="yyyy-MM-dd"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="设计年限" prop="designLife">
                  <el-input-number v-model="form.designLife" :min="0" placeholder="请输入设计年限" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="建筑高度" prop="buildingHeight">
                  <el-input-number v-model="form.buildingHeight" :precision="2" :step="0.01" placeholder="请输入建筑高度" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="总层数" prop="totalFloors">
                  <el-input-number v-model="form.totalFloors" :min="0" placeholder="请输入总层数" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="地上层数" prop="aboveFloors">
                  <el-input-number v-model="form.aboveFloors" :min="0" placeholder="请输入地上层数" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="地下层数" prop="underFloors">
                  <el-input-number v-model="form.underFloors" :min="0" placeholder="请输入地下层数" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单元总数" prop="unitCount">
                  <el-input-number v-model="form.unitCount" :min="0" placeholder="请输入单元总数" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="结构类型" prop="structureType">
                  <el-select v-model="form.structureType" placeholder="请选择结构类型">
                    <el-option
                      v-for="dict in dict.type.house_structure_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="地基类型" prop="foundationType">
                  <el-select v-model="form.foundationType" placeholder="请选择地基类型">
                    <el-option
                      v-for="dict in dict.type.house_foundation_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="房屋用途" prop="houseUsage">
                  <el-select v-model="form.houseUsage" placeholder="请选择房屋用途">
                    <el-option
                      v-for="dict in dict.type.house_usage_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="房屋类型" prop="houseType">
                  <el-select v-model="form.houseType" placeholder="请选择房屋类型">
                    <el-option
                      v-for="dict in dict.type.house_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="电梯设施" prop="hasElevator">
                  <el-select v-model="form.hasElevator" placeholder="请选择是否有电梯设施">
                    <el-option label="无" value="0" />
                    <el-option label="有" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="消防设施" prop="hasFireProtection">
                  <el-select v-model="form.hasFireProtection" placeholder="请选择是否有消防设施">
                    <el-option label="无" value="0" />
                    <el-option label="有" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="设计单位" prop="designUnit">
                  <el-input v-model="form.designUnit" placeholder="请输入设计单位" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="总户数" prop="totalHouseholds">
                  <el-input-number v-model="form.totalHouseholds" :min="0" placeholder="请输入总户数" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>

        <!-- 房屋照片标签页 -->
        <el-tab-pane label="房屋照片" name="photos">
          <el-form :model="form" label-width="100px">
            <el-form-item>
              <el-upload
                :action="upload.url"
                :headers="upload.headers"
                :file-list="photoList"
                :before-upload="handleBeforeUpload"
                :on-success="handleUploadSuccess"
                :on-remove="handleUploadRemove"
                :on-exceed="handleUploadExceed"
                :limit="10"
                multiple
                list-type="picture-card"
                accept=".jpg, .jpeg, .png"
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件且不超过5MB</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 评估信息标签页 -->
        <el-tab-pane label="评估信息" name="assessment">
          <el-form ref="form" :model="form" label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="鉴定等级" prop="appraisalLevel">
                  <el-select v-model="form.appraisalLevel" placeholder="请选择鉴定等级">
                    <el-option
                      v-for="dict in dict.type.house_appraisal_level"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排查等级" prop="inspectionLevel">
                  <el-select v-model="form.inspectionLevel" placeholder="请选择排查等级">
                    <el-option
                      v-for="dict in dict.type.house_inspection_level"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="抗震等级" prop="seismicLevel">
                  <el-select v-model="form.seismicLevel" placeholder="请选择抗震等级">
                    <el-option
                      v-for="dict in dict.type.house_seismic_level"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="风险等级" prop="riskLevel">
                  <el-select v-model="form.riskLevel" placeholder="请选择风险等级">
                    <el-option
                      v-for="dict in dict.type.house_risk_level"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="减隔震" prop="shockAbsorption">
                  <el-select v-model="form.shockAbsorption" placeholder="请选择是否采用减隔震">
                    <el-option
                      v-for="dict in dict.type.house_shock_absorption"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="保护建筑" prop="isProtected">
                  <el-select v-model="form.isProtected" placeholder="请选择是否保护性建筑">
                    <el-option
                      v-for="dict in dict.type.house_protected_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="改造方式" prop="isReformed">
                  <el-select v-model="form.isReformed" placeholder="请选择改造方式">
                    <el-option label="未改造" value="0" />
                    <el-option label="已改造" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物业管理" prop="hasProperty">
                  <el-select v-model="form.hasProperty" placeholder="请选择是否有物业管理">
                    <el-option label="无" value="0" />
                    <el-option label="有" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <div v-if="form.isReformed === '1'">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="改造单位" prop="reformDesignUnit">
                    <el-input v-model="form.reformDesignUnit" placeholder="请输入改造设计单位" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="改造时间" prop="reformTime">
                    <el-date-picker
                      v-model="form.reformTime"
                      type="date"
                      placeholder="选择改造时间"
                      value-format="yyyy-MM-dd"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="改造内容" prop="reformContent">
                    <el-input
                      type="textarea"
                      v-model="form.reformContent"
                      placeholder="请输入改造内容"
                      :rows="3"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <el-row>
              <el-col :span="24">
                <el-form-item label="备注说明" prop="remark">
                  <el-input
                    type="textarea"
                    v-model="form.remark"
                    placeholder="请输入备注说明"
                    :rows="3"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHouse, getHouse, delHouse, addHouse, updateHouse } from "@/api/house/house";
import { listHousePhoto, addHousePhoto, delHousePhoto } from "@/api/house/housePhoto";
import { getToken } from '@/utils/auth'
import { listProvinceOptions } from "@/api/house/province";
import { listCityOptions } from "@/api/house/city";
import { listDistrictOptions } from "@/api/house/district";
import { listStreetOptions } from "@/api/house/street";
import { listCommitteeOptions } from "@/api/house/committee";

export default {
  name: "House",
  dicts: [
    'house_risk_level',
    'house_structure_type',
    'house_usage_type',
    'house_land_nature',
    'house_property_nature',
    'house_foundation_type',
    'house_type',
    'house_inspection_level',
    'house_appraisal_level',
    'house_seismic_level',
    'house_shock_absorption',
    'house_protected_type'
  ],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房屋表格数据
      houseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        houseName: null,
        houseCode: null,
        province: null,
        city: null,
        district: null,
        riskLevel: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        houseName: [
          { required: true, message: "房屋名称不能为空", trigger: "blur" }
        ],
        houseCode: [
          { required: true, message: "房屋编号不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "地址不能为空", trigger: "blur" }
        ]
      },
      // 激活的标签页
      activeTab: 'basic',
      
      // 照片列表
      photoList: [],
      
      // 上传参数
      upload: {
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      // 省市区数据
      provinceOptions: [],
      cityOptions: [],
      districtOptions: [],
      // 查询表单省市区数据
      queryCityOptions: [],
      queryDistrictOptions: [],
      streetOptions: [],
      committeeOptions: []
    };
  },
  created() {
    this.getList();
    this.loadProvinceOptions();
  },
  methods: {
    /** 查询房屋列表 */
    getList() {
      this.loading = true;
      listHouse(this.queryParams).then(response => {
        this.houseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        houseId: undefined,
        houseName: undefined,
        houseCode: undefined,
        province: undefined,
        city: undefined,
        district: undefined,
        street: undefined,
        community: undefined,
        address: undefined,
        buildingArea: undefined,
        buildDate: undefined,
        riskLevel: undefined,
        longitude: undefined,
        latitude: undefined
      };
      this.resetForm("form");
      this.resetAddressOptions();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.province = null;
      this.queryParams.city = null;
      this.queryParams.district = null;
      this.queryCityOptions = [];
      this.queryDistrictOptions = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.houseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加房屋";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const houseId = row.houseId || this.ids;
      getHouse(houseId).then(async response => {
        this.form = response.data;
        // 按顺序加载省市区街道数据
        if (this.form.province) {
          await this.loadCityOptions(this.form.province);
        }
        if (this.form.city) {
          await this.loadDistrictOptions(this.form.city);
        }
        if (this.form.district) {
          await this.loadStreetOptions(this.form.district);
        }
        // 如果有街道编码，加载居委会选项
        if (this.form.street) {
          await this.loadCommitteeOptions(this.form.street);
        }
        // 获取照片列表
        this.getPhotoList(houseId);
        this.open = true;
        this.title = "修改房屋";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.houseId != null) {
            updateHouse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHouse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const houseIds = row.houseId || this.ids;
      this.$modal.confirm('是否确认删除房屋编号为"' + houseIds + '"的数据？').then(function() {
        return delHouse(houseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 上传前检查文件 */
    handleBeforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    
    /** 上传成功回调 */
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 上传成功后保存照片信息
        const photoData = {
          houseId: this.form.houseId,
          photoUrl: response.url,
          photoDesc: file.name
        };
        // 调用保存照片接口
        addHousePhoto(photoData).then(response => {
          this.$modal.msgSuccess("上传成功");
          this.getPhotoList(this.form.houseId);
        });
      } else {
        this.$modal.msgError(response.msg);
      }
    },
    
    /** 删除上传文件 */
    handleUploadRemove(file) {
      // 调用删除照片接口
      delHousePhoto(file.photoId).then(response => {
        this.$modal.msgSuccess("删除成功");
        this.getPhotoList(this.form.houseId);
      });
    },
    
    /** 限制上传数量 */
    handleUploadExceed() {
      this.$message.warning(`上传文件数量不能超过 10 个!`);
    },
    
    /** 获取照片列表 */
    getPhotoList(houseId) {
      listHousePhoto(houseId).then(response => {
        this.photoList = response.data.map(item => {
          return {
            photoId: item.photoId,
            name: item.photoDesc,
            url: item.photoUrl
          };
        });
      });
    },
    /** 加载省份数据 */
    loadProvinceOptions() {
      listProvinceOptions().then(response => {
        this.provinceOptions = response.rows.map(item => ({
          value: item.provinceCode,
          label: item.provinceName
        }));
      });
    },
    /** 加载城市数据 */
    loadCityOptions(provinceCode) {
      listCityOptions({ provinceCode: provinceCode }).then(response => {
        this.cityOptions = response.rows.map(item => ({
          value: item.cityCode,
          label: item.cityName
        }));
      });
    },
    /** 加载区域数据 */
    loadDistrictOptions(cityCode) {
      listDistrictOptions({ cityCode: cityCode }).then(response => {
        this.districtOptions = response.rows.map(item => ({
          value: item.districtCode,
          label: item.districtName
        }));
      });
    },
    /** 加载街道数据 */
    loadStreetOptions(districtCode) {
      listStreetOptions({ districtCode: districtCode }).then(response => {
        this.streetOptions = response.rows.map(item => ({
          value: item.streetCode,
          label: item.streetName
        }));
      });
    },
    /** 加载居委数据 */
    loadCommitteeOptions(streetCode) {
      if (!streetCode) {
        this.committeeOptions = [];
        return;
      }
      listCommitteeOptions({ streetCode: streetCode, pageSize: 100 }).then(response => {
        console.log('Committee API response:', response);
        this.committeeOptions = response.rows.map(item => ({
          value: item.committeeCode,
          label: item.committeeName
        }));
        console.log('All committee options:', this.committeeOptions);
      });
    },
    /** 省份选择改变事件 */
    handleProvinceChange(value) {
      if (value) {
        this.loadCityOptions(value);
        this.form.city = null;
        this.form.district = null;
        this.form.street = null;
        this.form.community = null;
        this.cityOptions = [];
        this.districtOptions = [];
        this.streetOptions = [];
        this.committeeOptions = [];
      }
    },
    /** 城市选择改变事件 */
    handleCityChange(value) {
      if (value) {
        this.loadDistrictOptions(value);
        this.form.district = null;
        this.form.street = null;
        this.form.community = null;
        this.districtOptions = [];
        this.streetOptions = [];
        this.committeeOptions = [];
      }
    },
    /** 区域选择改变事件 */
    handleDistrictChange(value) {
      if (value) {
        this.loadStreetOptions(value);
        this.form.street = null;
        this.form.community = null;
        this.streetOptions = [];
        this.committeeOptions = [];
      }
    },
    /** 街道选择改变事件 */
    handleStreetChange(value) {
      console.log('Street changed:', value);
      if (value) {
        this.form.community = null;
        this.committeeOptions = [];
        this.loadCommitteeOptions(value);
      } else {
        this.form.community = null;
        this.committeeOptions = [];
      }
    },
    /** 居委选择改变事件 */
    handleCommitteeChange(value) {
      console.log('Committee changed:', value);
      this.form.community = value;
      console.log('Updated form.community:', this.form.community);
    },
    /** 重置地址选项 */
    resetAddressOptions() {
      this.cityOptions = [];
      this.districtOptions = [];
      this.streetOptions = [];
      this.committeeOptions = [];
    },
    /** 加载查询表单城市数据 */
    loadQueryCityOptions(provinceCode) {
      listCityOptions({ provinceCode: provinceCode }).then(response => {
        this.queryCityOptions = response.rows.map(item => ({
          value: item.cityCode,
          label: item.cityName
        }));
      });
    },
    /** 加载查询表单区域数据 */
    loadQueryDistrictOptions(cityCode) {
      listDistrictOptions({ cityCode: cityCode }).then(response => {
        this.queryDistrictOptions = response.rows.map(item => ({
          value: item.districtCode,
          label: item.districtName
        }));
      });
    },
    /** 查询表单省份选择改变事件 */
    handleQueryProvinceChange(value) {
      if (value) {
        this.loadQueryCityOptions(value);
        this.queryParams.city = null;
        this.queryParams.district = null;
        this.queryDistrictOptions = [];
      } else {
        this.queryCityOptions = [];
        this.queryDistrictOptions = [];
        this.queryParams.city = null;
        this.queryParams.district = null;
      }
    },
    /** 查询表单城市选择改变事件 */
    handleQueryCityChange(value) {
      if (value) {
        this.loadQueryDistrictOptions(value);
        this.queryParams.district = null;
      } else {
        this.queryDistrictOptions = [];
        this.queryParams.district = null;
      }
    },
  }
};
</script> 